<template>
  <div class="order-profile-page">
    <!-- 返回按钮 -->
    <div class="back-section">
      <el-button @click="goBack" type="primary" icon="ArrowLeft">
        返回商品页面
      </el-button>
    </div>

    <h2>确认订单</h2>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      加载中...
    </div>

    <!-- 错误状态 -->
    <div v-else-if="!goods || Object.keys(goods).length === 0" class="error">
      未找到商品信息
    </div>

    <!-- 订单信息 -->
    <div v-else class="order-container">
      <div class="order-item">
        <div class="item-image">
          <img :src="goods.image || '@/assets/default-goods.png'" :alt="goods.name" class="goods-image" />
        </div>
        <div class="item-details">
          <h3>{{ goods.name }}</h3>
          <p class="item-price">¥{{ goods.price }}</p>
          <div class="quantity-control">
            <span>数量:</span>
            <el-input-number v-model="quantity" :min="1" :max="99" />
          </div>
        </div>
      </div>

      <!-- 收货地址部分 -->
      <div class="delivery-address-section">
        <h3>收货信息</h3>
        <el-form label-width="100px">
          <!-- 地址选择下拉框 -->
          <el-form-item label="选择收货信息">
            <el-select v-model="selectedAddressId" placeholder="请选择收货信息" style="width: 100%;">
              <el-option
                  v-for="addr in userAddresses"
                  :key="addr.id"
                  :label="formatAddress(addr)"
                  :value="addr.id">
              </el-option>
            </el-select>
            <el-button @click="showAddAddressDialog" type="primary" style="margin-left: 10px;">新增收货信息</el-button>
          </el-form-item>

          <!-- 显示选中地址详情 -->
          <div v-if="selectedAddress" class="selected-address-details">
            <p><strong>收货人:</strong> {{ selectedAddress.receiver_name }}</p>
            <p><strong>联系电话:</strong> {{ selectedAddress.receiver_phone }}</p>
            <p><strong>地址:</strong> {{ selectedAddress.province }}{{ selectedAddress.city }}{{ selectedAddress.district }}{{ selectedAddress.detail_addr }}</p>
          </div>
        </el-form>
      </div>

      <div class="order-summary">
        <div class="summary-row">
          <span>商品总价:</span>
          <span>¥{{ (goods.price * quantity).toFixed(2) }}</span>
        </div>
        <div class="summary-row total">
          <span>总计:</span>
          <span>¥{{ (goods.price * quantity).toFixed(2) }}</span>
        </div>
      </div>

      <div class="order-actions">
        <el-button type="success" size="large" @click="submitOrder">
          提交订单
        </el-button>
      </div>
    </div>

    <!-- 新增地址对话框 -->
    <el-dialog v-model="addAddressDialogVisible" title="新增收货地址" width="500px">
      <el-form :model="newAddressForm" ref="addressFormRef" label-width="100px">
        <el-form-item label="收货人" prop="receiver_name" :rules="[{ required: true, message: '请输入收货人姓名', trigger: 'blur' }]">
          <el-input v-model="newAddressForm.receiver_name" placeholder="请输入收货人姓名"></el-input>
        </el-form-item>

        <el-form-item label="联系电话" prop="receiver_phone" :rules="[{ required: true, message: '请输入联系电话', trigger: 'blur' }]">
          <el-input v-model="newAddressForm.receiver_phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>

        <el-form-item label="省份" prop="province" :rules="[{ required: true, message: '请输入省份', trigger: 'blur' }]">
          <el-input v-model="newAddressForm.province" placeholder="请输入省份"></el-input>
        </el-form-item>

        <el-form-item label="城市" prop="city" :rules="[{ required: true, message: '请输入城市', trigger: 'blur' }]">
          <el-input v-model="newAddressForm.city" placeholder="请输入城市"></el-input>
        </el-form-item>

        <el-form-item label="区/县" prop="district" :rules="[{ required: true, message: '请输入区/县', trigger: 'blur' }]">
          <el-input v-model="newAddressForm.district" placeholder="请输入区/县"></el-input>
        </el-form-item>

        <el-form-item label="详细地址" prop="detail_addr" :rules="[{ required: true, message: '请输入详细地址', trigger: 'blur' }]">
          <el-input v-model="newAddressForm.detail_addr" placeholder="请输入详细地址" type="textarea"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addAddressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveNewAddress">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, reactive, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import goodsApi from '@/api/goods_api.js'
import deliveryAddrApi from '@/api/deliveryAddr_api.js'
import orderApi from '@/api/order_api.js'  // 引入订单API
import orderAddrApi from '@/api/orderAddr_api.js'  // 引入订单地址API
import { ArrowLeft } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import loginApi from "@/api/login_api.js";

export default {
  name: 'OrderProfilePage',
  components: {
    ArrowLeft
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const goods = ref({})
    const loading = ref(false)
    const quantity = ref(1)
    const userAddresses = ref([])
    const selectedAddressId = ref('')
    const addAddressDialogVisible = ref(false)
    const addressFormRef = ref(null)
    const currentUser = ref(null)  // 存储当前用户信息

    // 新增地址表单
    const newAddressForm = reactive({
      receiver_name: '',
      receiver_phone: '',
      province: '',
      city: '',
      district: '',
      detail_addr: '',
      user_id: 1 // 这里应该从登录用户信息中获取
    })

    // 计算属性：获取选中的地址对象
    const selectedAddress = computed(() => {
      return userAddresses.value.find(addr => addr.id === selectedAddressId.value)
    })

    // 获取商品详情
    const fetchGoodsDetail = async (id) => {
      if (!id) return

      loading.value = true
      try {
        const res = await goodsApi.getGoodsById(id)
        if (res || res.code === 200) {
          goods.value = res || {}
        } else {
          console.error('获取商品详情失败:', res)
        }
      } catch (err) {
        console.error('获取商品详情失败:', err)
      } finally {
        loading.value = false
      }
    }

    // 获取用户信息（新增方法）
    const fetchUserInfo = async () => {
      try {
        const userRes = await loginApi.logininfo();
        currentUser.value = userRes
        return userRes
      } catch (err) {
        console.error('获取用户信息失败:', err)
        ElMessage.error('请先登录')
        router.push('/login')  // 跳转到登录页
        return null
      }
    }

    // 获取用户地址列表
    const fetchUserAddresses = async () => {
      const user = await fetchUserInfo()
      if (!user) return

      try {
        const userId = user.id
        const res = await deliveryAddrApi.getAddrsByUserId(userId)
        console.log("Addr_res", res);
        if (res || res.code === 200) {
          userAddresses.value = res || []
          // 如果有地址，默认选择第一个
          if (userAddresses.value.length > 0) {
            selectedAddressId.value = userAddresses.value[0].id
          }
        }
      } catch (err) {
        console.error('获取用户地址失败:', err)
        ElMessage.error('获取地址信息失败')
      }
    }

    // 显示新增地址对话框
    const showAddAddressDialog = async () => {
      const user = await fetchUserInfo()
      if (!user) return

      // 重置表单
      Object.assign(newAddressForm, {
        receiver_name: '',
        receiver_phone: '',
        province: '',
        city: '',
        district: '',
        detail_addr: '',
        user_id: user.id
      })
      addAddressDialogVisible.value = true
    }

    // 保存新增地址
    const saveNewAddress = async () => {
      addressFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            const res = await deliveryAddrApi.addAddr(newAddressForm)
            console.log('保存地址结果:', res)
            if (res && res !== "undefined") {
              ElMessage.success('地址保存成功')
              addAddressDialogVisible.value = false
              // 重新获取地址列表
              await fetchUserAddresses()
            } else {
              ElMessage.error(res?.message || '地址保存失败')
            }
          } catch (err) {
            console.error('保存地址失败:', err)
            ElMessage.error('保存地址失败')
          }
        }
      })
    }

    // 格式化地址显示
    const formatAddress = (addr) => {
      return `${addr.province}${addr.city}${addr.district}${addr.detail_addr} (${addr.receiver_name})`
    }

    // 返回上一页
    const goBack = () => {
      router.go(-1)
    }

    // 提交订单
    // 提交订单
    const submitOrder = async () => {
      if (!selectedAddress.value) {
        ElMessage.warning('请选择收货地址')
        return
      }

      if (!currentUser.value) {
        ElMessage.warning('请先登录')
        router.push('/login')
        return
      }

      if (!goods.value.id) {
        ElMessage.warning('商品信息有误')
        return
      }

      try {
        // 检查商品库存
        const goodsDetail = await goodsApi.getGoodsById(goods.value.id)
        console.log("goodsDetail", goodsDetail);
        if (!goodsDetail || goodsDetail.stock < quantity.value) {
          ElMessage.error('商品库存不足，无法生成订单')
          return
        }

        // 先创建订单地址记录
        const fullAddress = `${selectedAddress.value.province}${selectedAddress.value.city}${selectedAddress.value.district}${selectedAddress.value.detail_addr}`;

        const orderAddrData = {
          user_id: currentUser.value.id,
          goods_id: goods.value.id,
          address: fullAddress,
          is_del: 0  // 删除状态，默认为0（未删除）
        };

        const orderAddrRes = await orderAddrApi.addOrderAddr(orderAddrData);
        if (!orderAddrRes) {
          ElMessage.error('订单地址创建失败')
          return
        }

        // 通过用户ID和商品ID查询刚创建的订单地址
        const orderAddrsRes = await orderAddrApi.getOrderAddrsByGoodsId(goods.value.id);

        console.log('订单地址数据:', orderAddrsRes);
        // 构造订单数据，包含订单地址ID
        const orderData = {
          user_id: currentUser.value.id,
          goods_id: goods.value.id,
          delivery_addr_id: selectedAddress.value.id,
          order_addr_id: orderAddrsRes[0].id,  // 添加订单地址ID
          goods_name: goods.value.name,
          goods_count: quantity.value,
          goods_price: goods.value.price,
          status: 0  // 0表示未支付
        }

        // 调用订单API创建订单
        const orderRes = await orderApi.addOrder(orderData)

        console.log('订单数据:', orderData)
        if (orderRes) {
          // 更新商品库存
          const updatedGoods = {
            ...goodsDetail,
            stock: goodsDetail.stock - quantity.value
          }
          await goodsApi.updateGoods(updatedGoods)

          ElMessage.success('订单创建成功')
          // 跳转到订单详情页或订单列表页
          await router.push(`/user/orderList`)
        } else {
          ElMessage.error('订单创建失败')
        }
      } catch (err) {
        console.error('提交订单失败:', err)
        ElMessage.error('提交订单失败，请稍后重试: ' + err.message)
      }
    }

    // 页面加载时获取商品详情和用户地址
    onMounted(() => {
      const goodsId = route.params.id || route.query.id
      fetchGoodsDetail(goodsId)
      fetchUserAddresses()
    })

    return {
      goods,
      loading,
      quantity,
      userAddresses,
      selectedAddressId,
      selectedAddress,
      addAddressDialogVisible,
      newAddressForm,
      addressFormRef,
      goBack,
      submitOrder,
      showAddAddressDialog,
      saveNewAddress,
      formatAddress
    }
  }
}
</script>

<style scoped>
/* 样式部分保持不变 */
.order-profile-page {
  background-color: #fff;
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.back-section {
  margin-bottom: 20px;
}

.order-container {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 20px;
}

.order-item {
  display: flex;
  gap: 20px;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.item-image {
  flex: 0 0 120px;
}

.goods-image {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
}

.item-details {
  flex: 1;
}

.item-details h3 {
  margin: 0 0 10px 0;
  color: #333;
}

.item-price {
  font-size: 18px;
  color: #e64340;
  font-weight: bold;
  margin: 10px 0;
}

.quantity-control {
  display: flex;
  align-items: center;
  gap: 10px;
}

.delivery-address-section {
  margin: 20px 0;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.delivery-address-section h3 {
  margin-top: 0;
  color: #333;
}

.selected-address-details {
  margin-top: 15px;
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #eee;
}

.selected-address-details p {
  margin: 5px 0;
}

.order-summary {
  margin: 20px 0;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
}

.summary-row.total {
  font-size: 18px;
  font-weight: bold;
  border-top: 1px solid #ddd;
  margin-top: 10px;
  padding-top: 10px;
}

.order-actions {
  text-align: right;
  margin-top: 20px;
}

.loading, .error {
  text-align: center;
  padding: 50px 20px;
  color: #999;
  font-size: 18px;
}

@media (max-width: 768px) {
  .order-item {
    flex-direction: column;
  }

  .item-image {
    flex: 0 0 auto;
  }

  .order-actions {
    text-align: center;
  }
}
</style>
